package com.lanmao.emc.utils;

import com.lanmao.emc.function.SFunction;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;

/**
 * 描述：
 *
 * @author lanmao
 * @since 2024年11月11日 20:42
 */
public class FieldUtils {

    public static <T> String val(SFunction<T, ?> func) {
        try {
            if (func == null) {
                throw new Exception("不支持的类型");
            }
            Method method = func.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(true);
            SerializedLambda invoke = (SerializedLambda) method.invoke(func);
            String methodName = invoke.getImplMethodName();
            return resolveFieldName(methodName);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String resolveFieldName(String methodName) {
        if (methodName.startsWith("get")) {
            methodName = methodName.substring(3);
        }
        if (methodName.startsWith("is")) {
            methodName = methodName.substring(2);
        }
        return camelToLowerCase(methodName);
    }

    private static String camelToLowerCase(String methodName) {
        return methodName.replaceAll("[A-Z]", "_$0").toLowerCase().substring(1);
    }
}